package com.example.resume_management_system.Controller;

import com.example.resume_management_system.Variable.Variable;
import com.example.resume_management_system.common.Result;
import com.example.resume_management_system.dto.LoginForm;
import com.example.resume_management_system.pojo.User;
import com.example.resume_management_system.service.UserService;
import com.example.resume_management_system.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    ResultUtil resultUtil;

    @PostMapping("/login")
    public Result login(@RequestBody LoginForm loginForm, HttpServletRequest request){

        User user = userService.getUserByAccount(loginForm.getAccount());
        System.out.println(user);
        if(user == null){
            return resultUtil.error(400,"账户不存在");
        }else if(!user.getPassWord().equals(loginForm.getPassword())){
            return resultUtil.error(400,"密码错误");
        }else{
            HttpSession session = request.getSession();
            session.setAttribute("account",loginForm.getAccount());
            Variable.account=loginForm.getAccount();
            user.setPassWord(null);
            return resultUtil.ok(200,"登录成功",user);
        }
    }

    @PostMapping("/register")
    public Result register(@RequestBody User user, HttpServletRequest request){
        String check = validateReg(user);
        if(check != null)
            return resultUtil.error(400,check);
        int i = userService.register(user);
        if(i == 1){
            HttpSession session = request.getSession();
            session.setAttribute("account",user.getAccount());
            return resultUtil.ok(200,"注册成功");
        }else if(i == -1){
            return resultUtil.error(400,"账户已存在");
        }else{
            return resultUtil.error(400,"注册失败");
        }
    }

    @PutMapping("/loginOut")
    public Result loginOut(HttpServletRequest request){
        HttpSession session = request.getSession();
        String account = (String)session.getAttribute("account");
        if(account == null){
            return resultUtil.error(400,"尚未登录");
        }
        session.invalidate();
        return resultUtil.ok(200,"退出成功");
    }

    @GetMapping("/test")
    public String test(){
        System.out.println("123");
        return "abc";
    }

    private String validateReg(User user){
        if(user == null)
            return "传入参数为空";
        if(user.getSex() != '男' && user.getSex() != '女')
            return "性别只能为男或女";
        return null;
    }

}
